package com.offcn.utils;
/**
 * 封装连接池工具类
 * 目的： 让程序运行到结束都只有一个连接池对象
 *   作用： 用户可以从工具类获得数据库连接对象
 *   并发
 */

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class JdbcUtils {
private  static  ComboPooledDataSource dataSource;
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();//
//创建连接池   连接池只需创建一次使用静态代码快
    static {
      dataSource = new   ComboPooledDataSource();
    }


    //获取数据库连接
    public static Connection getConnection() throws SQLException {
        //当前线程下是否有可以直接使用的数据库连接
        Connection connection = threadLocal.get();
        if (connection==null){
            connection = dataSource.getConnection();
            threadLocal.set(connection);
        }
        return connection;

    }

    //关闭数据库资源
    public static  void close(){
        try {
            Connection connection = threadLocal.get();
            threadLocal.remove();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
